
const parse = function (source) {
  const reg = /\n\S/g
  let res = ''
  let indexList = []
  let parseObj = {}
  while(res = reg.exec(source)){
    indexList.push(res.index)
  }

  let afterSplit = []
  let startIndex = 0
  for (let index of indexList) {
    afterSplit.push(source.substring(startIndex, index))
    startIndex = index + 1
  }
  if (indexList[indexList.length - 1] < source.length) {
    afterSplit.push(source.substring(startIndex))
  }
  if (afterSplit.length < 1 && source.indexOf(':') > 0) {
    afterSplit.push(source)
  }
  for (let pairs of afterSplit) {
    const searchIndex = pairs.search(/:\n/)
    if (searchIndex > 0) {
      let parseStr = pairs.substring(searchIndex + 1).trim().replace(/\n  /g, '\n')
      const subParseObj = parse(parseStr)
      parseObj[pairs.substring(0,searchIndex)] = subParseObj
      continue
    } else {
      // 是值
      const pairsList = pairs.split(':')
      if (pairsList.length > 1) {
        parseObj[pairsList[0]] = pairsList[1]
      }
    }
  }
  return parseObj
}

module.exports = parse